﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Documents;

namespace Knowledgecast.Twitter.WPF
{
    public class StatusSourceConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            List<Inline> inlines = new List<Inline>();
            string source = value as string;
            if (String.IsNullOrEmpty(source) == false)
            {
                inlines.Add(new Run(" via "));

                if (source.StartsWith("<a"))
                {
                    int anchorClose = source.IndexOf('>') + 1;
                    int urlStart = source.IndexOf("href=\"") + "href\"".Length + 1;
                    string sourceName = null;
                    string sourceUrl = null;

                    if (anchorClose > 0)
                    {
                        sourceName = source.Substring(anchorClose, source.LastIndexOf('<') - anchorClose);
                    }

                    if (urlStart > 0)
                    {
                        sourceUrl = source.Substring(urlStart, source.LastIndexOf('\"') - urlStart);
                    }

                    if (Uri.IsWellFormedUriString(sourceUrl, UriKind.Absolute))
                    {
                        Hyperlink link = new Hyperlink();
                        link.NavigateUri = new Uri(sourceUrl, UriKind.Absolute);
                        link.Command = TwitterCommands.ShowUrl;
                        link.CommandParameter = sourceUrl;
                        link.Inlines.Add(new Run(sourceName));

                        inlines.Add(link);
                    }
                    else
                    {
                        inlines.Add(new Run(source));
                    }
                }
                else
                {
                    inlines.Add(new Run(source));
                }
            }

            return inlines;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
